package com.andiary.common.note;



import com.andiary.common.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.telephony.gsm.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class SendSMS extends Activity implements TextWatcher {
	
    private ImageButton btnNote;
    private ImageButton btnInfo;
    private Button btnSend; 
    private EditText ad;
    private TextView adcontact;
    private AutoCompleteTextView contact;
    private String mobilephone;
    private String namePerson;
    private String mobilephonenumber;

	String [] mStrinamo;
	String N=null;
	int	nameColumnIndex;

	 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         
         setContentView(R.layout.smscontact);
         
         btnNote = (ImageButton) findViewById (R.id.day);
         btnNote.setOnClickListener(btnNoteListener);

         btnInfo = (ImageButton) findViewById (R.id.info);
         btnInfo.setOnClickListener(btnInfoListener);
         
         btnSend = (Button) findViewById(R.id.send);
         btnSend.setOnClickListener(btnSendListener);
         
         contact= (AutoCompleteTextView) findViewById (R.id.contact);
       
         adcontact= (TextView) findViewById (R.id.adcontact); 
         ad=(EditText) findViewById (R.id.sms);       
         ad.requestFocus();

     	ContentResolver content=getContentResolver();
     	Cursor cursor= content.query(People.CONTENT_URI, PEOPLE_PROJECTION, 
     			null, null, People.NAME);
     	ContactListAdapter adapter= new ContactListAdapter (this, cursor);
     	contact.addTextChangedListener(this);
     	contact.setAdapter(adapter);		
    }
 
public void onTextChanged(CharSequence s, int start, int before, 
            int count) { 
	
	String name= s.toString();
	Cursor	nameCursor = managedQuery(People.CONTENT_URI, new String[] {
 			People._ID, People.NAME }, null, null, People.NAME);

 	if (nameCursor.moveToFirst()) {		
 		
 		do { 
			nameColumnIndex = nameCursor.getInt(nameCursor.getColumnIndex(People.NAME));
			
			if (name.equals(nameCursor.getString(nameCursor.getColumnIndex(People.NAME)))) {
					
					Uri.Builder builder = People.CONTENT_URI.buildUpon();
			 		ContentUris.appendId(builder, nameCursor
			 				.getLong(nameColumnIndex));
			 		builder.appendEncodedPath(People.Phones.CONTENT_DIRECTORY);
			 		
			 		Uri phoneNumbersUri = builder.build();
			 		
			 	Cursor	phonesForPerson = managedQuery(phoneNumbersUri, new String[] {
			 				People.Phones._ID, People.Phones.NUMBER,
			 				People.Phones.TYPE,People.Phones.NAME}, null, null,null);

			 	if (phonesForPerson.moveToFirst()) {
			 		do {
			 			int typeOfPhone = phonesForPerson
			 					.getInt(phonesForPerson
			 							.getColumnIndex(People.Phones.TYPE));
			 			
			 			if(typeOfPhone==People.Phones.TYPE_MOBILE){
			 				mobilephone=phonesForPerson
													.getString(phonesForPerson
															.getColumnIndex(People.Phones.NUMBER)) ;
			 				ad.setText(mobilephone);
			 				btnSend.requestFocus();
			 				
			 				}
			 			
			 			}	while (phonesForPerson.moveToNext());
			 		
			 		 }              
					break;
				}
		
 		}	while (nameCursor.moveToNext());
 		
 	}

} 

public void beforeTextChanged(CharSequence s, int start, 
                int count, int after) { 
// needed for interface, but not used 
	
} 

public void afterTextChanged(Editable s) { 
// needed for interface, but not used 
} 

	private Button.OnClickListener btnNoteListener= new Button.OnClickListener() {

		public void onClick(View view) {               
			setResult(RESULT_OK);
			finish();
		}
  
	};
	
    private Button.OnClickListener btnInfoListener= new Button.OnClickListener() {

    	public void onClick(View view) {
	
        //	Intent info = new Intent(SendSMS.this,.Info.class);
    	  //  startActivity(info);
    	//	finish();
    	
    	}
  
    };   
    private Button.OnClickListener btnSendListener= new Button.OnClickListener() {

    	public void onClick(View view) {
    		
    		mobilephonenumber=ad.getText().toString();;
  	      
      		new AlertDialog.Builder(SendSMS.this)            	
              
              .setMessage("Sent SMS to "+mobilephonenumber+" ?")
          
              .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                     
                  
    		  String textSMS= "r";
    		  //(getString(
    	      // note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE))+"  "+getString(
    	                  //  note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY))); 

    				SmsManager smsManager = SmsManager.getDefault();
    			    String destAddr =  mobilephonenumber;

    			    try {
    			     PendingIntent il = PendingIntent.getBroadcast(SendSMS.this, 0, new Intent(), 0);
    			     smsManager.sendTextMessage(destAddr, null, textSMS, il, null);
    			     
    			     Log.i("TEST", "message envoyer a l'adresse: "+destAddr);
    	  			 Toast.makeText(SendSMS.this, "Your message have been sent", Toast.LENGTH_SHORT).show();
    	  			 
    			    } catch (Exception e) {
    			    	
    			      Log.i("TEST", e.toString());
    			      Toast.makeText(SendSMS.this, "type a correct phone number", Toast.LENGTH_LONG).show();
    			    }
    			    		ad.requestFocus();
                  }
                  })
                  
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int whichButton) {
                      	  	ad.requestFocus();
                       }
                   })
                   .show();
    			}
    	};
    	public static class ContactListAdapter extends CursorAdapter implements Filterable {
            public ContactListAdapter(Context context, Cursor c) {
                super(context, c);
                mContent = context.getContentResolver();
            }

            @Override
            public View newView(Context context, Cursor cursor, ViewGroup parent) {
            	
                final LayoutInflater inflater = LayoutInflater.from(context);
                final TextView view = (TextView) inflater.inflate(
                        android.R.layout.simple_dropdown_item_1line, parent, false);
                
                view.setText(cursor.getString(1));
                return view;
            }

            @Override
            public void bindView(View view, Context context, Cursor cursor) {
                ((TextView) view).setText(cursor.getString(1));
            }

            @Override
            public String convertToString(Cursor cursor) {
                return cursor.getString(1);
            }

            @Override
            public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
                if (getFilterQueryProvider() != null) {
                    return getFilterQueryProvider().runQuery(constraint);
                }

                StringBuilder buffer = null;
                String[] args = null;
                if (constraint != null) {
                    buffer = new StringBuilder();
                    buffer.append("UPPER(");
                    buffer.append(Contacts.People.NAME);
                    buffer.append(") GLOB ?");
                    args = new String[] { constraint.toString().toUpperCase() + "*" };
                }

                return mContent.query(Contacts.People.CONTENT_URI, PEOPLE_PROJECTION,
                        buffer == null ? null : buffer.toString(), args,
                        		Contacts.People.NAME);
            }

            private ContentResolver mContent;        
        }

        private static final String[] PEOPLE_PROJECTION = new String[] {
        	Contacts.People._ID,
        	Contacts.People.NAME,
        
        };

}
   

